<?php
class buxfer
{

	protected $transactions = array();
  protected $token;
  private $account;
  private $ch;
  protected $transactionsToAdd = array();
  const base = "https://www.buxfer.com/api";  
	
   function __construct() 
    { 
      
# XXX WARNING: only a sample; please do NOT hard-code your username 
# or passwords in this manner in your API clients

$username = "giacomo.morittu@gmail.com"; 
//$username = "zerosottozero@gmail.com";  
$password = "omerdaeio"; 


#############



$url = $this::base."/login.json?userid=$username&password=$password";
$this->ch = curl_init ($url);
curl_setopt ($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($this->ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($this->ch, CURLOPT_HEADER, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($this->ch);
$response = json_decode (curl_exec ($this->ch), true);
$response = $response ['response'];
$this->checkError ($response);
$this->token = $response ['token'];
$this->get_transactions();
//echo var_dump($this->transactions);

//exit(0);  



//foreach ($response ['budgets'] as $budget) { 
//    print sprintf ("%12s %8s %10.2f %10.2f\n", $budget ['name'], $budget ['currentPeriod'], $budget ['limit'], $budget ['remaining']);
//}

 }
   
   private function checkError ($response) {
    if ($response['status'] != "OK") {
        $error = str_replace ("ERROR: ", "", $response ['status']);
        $stderr = fopen ("php://stderr", "w");
        fprintf ($stderr, "An error occured: %s\n", $error);
        fflush ($stderr);
        throw new Exception($error);   
    }
}

    public function set_account($account){
     $this->account = $account;
    }

   public function get_accounts(){
    $url = $this::base."/accounts.json?token=$this->token";
    curl_setopt ($this->ch, CURLOPT_URL, $url);
    $response = json_decode (curl_exec ($this->ch), true);
    $this->checkError ($response['response']);
    return $response['response']['accounts'];
   
   }

   private function get_transactions($page = 1){
    $url = $this::base."/transactions.json?token=$this->token&page=".$page;
    curl_setopt ($this->ch, CURLOPT_URL, $url);
    $response = json_decode (curl_exec ($this->ch), true);
    $this->checkError ($response['response']);
    if($page == 1){
      $this->transactions = $response ['response']['transactions'];
    }
    else{
      foreach($response ['response']['transactions'] as $temp){
        $this->transactions[] = $temp;  
      }
    }
    if($response['response']['numTransactions'] > (25 * $page)) {
       $this->get_transactions($page + 1) ;
    }
    }
    
    private function get_transaction($startDate,$endDate){
    $url = $this::base."/transactions.json?token=$this->token"."&startDate=".$startDate."&endDate=".$endDate."&accountName=".$this->account;
    curl_setopt ($this->ch, CURLOPT_URL, $url);
    $response = json_decode (curl_exec ($this->ch), true);
    $this->checkError ($response['response']);
    return $response ['response']['transactions'];
    if($response['response']['numTransactions'] > 25) {
      ECHO "ATTENZIONEEEEEEEEEEEEEEEEEEEEEEee controllo sul numero transaction"           ;
    }
    
  }
  
   public function compare($transactionToCompare){
    $add = 0;
    try{
    $transactions = $this->get_transaction($transactionToCompare['date'],$transactionToCompare['date']);
    foreach($transactions as $transaction){
     $date = $this->xl2timestamp($transactionToCompare['date']);
     $quoz = $transactionToCompare['amount'] / $transaction['amount'] ;
      if(trim($transactionToCompare['description']) === trim($transaction['description']) and $quoz == 1){
          $add = 1;
          continue;
      }
    }
    }catch (Exception $e)    {
     echo $e->getMessage();
     }
    if($add == 0){
      $this->transactionsToAdd[] = $transactionToCompare;
       }
  }

    
    private function add_transaction($transaction){
      // DESCRIPTION [+]AMOUNT [TAGS:<tags>] [ACCT:<accounts>] [DATE:<date>] [STATUS:<status>]
      $content = $transaction['description']." ".$transaction['amount']." DATE:".$transaction['date'];
        
      $data = array(
        'format' => 'sms',
        'text' => $content,
        'token' =>  $this->token);
        
      $url = $this::base."/add_transaction.json";
      $ch = curl_init ($url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt($ch,  CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $response = json_decode (curl_exec ($ch), true);
      $this->checkError ($response['response']);
    }
    
    public function add_transactions(){
      $content = null;
      for($i = 0; $i < count($this->transactionsToAdd); $i++){
      $transaction = $this->transactionsToAdd[$i]   ;
      
      // DESCRIPTION [+]AMOUNT [TAGS:<tags>] [ACCT:<accounts>] [DATE:<date>] [STATUS:<status>]
      $content = $content.$transaction['description']." ".$transaction['amount']." DATE:".$transaction['date']." ACCT:".$this->account." TAGS:".$this->calc_correlaction($transaction['description']);
      if($i < (count($this->transactionsToAdd) - 1))   {
          $content = $content.";";
      }
      
      
      }
      
        
      $data = array(
        'format' => 'sms',
        'text' => $content,
        'token' =>  $this->token);
        
      $url = $this::base."/add_transaction.json";
      $ch = curl_init ($url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt($ch,  CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $response = json_decode (curl_exec ($ch), true);

      $this->checkError ($response['response']);
    }
    
   private function xl2timestamp($xl_date) {
      $dt = new DateTime($xl_date);
		  $timestamp =  date('d M',$dt->getTimestamp()) ;
      return $timestamp;
		}
    
   public function calc_correlaction($description){
    $best_p = 0;
    $tag = null;
    foreach($this->transactions as $transaction){
      if($transaction['tags'] != null){    
        similar_text($description,$transaction['description'],$p);
        if($p == 100){
          return $transaction['tags']   ;
        }else
        if($p > $best_p and $p > 40){
          $best_p = $p                 ;
          $tag =  $transaction['tags'];
        //  echo "<p>".$transaction['description']."---".$description."------".$p."</p>";
          }
      }   
    }
    return $tag;
   
   
   } 
    
	 

	
}

?>